package com.card.user;

import java.util.Date;

import org.jboss.netty.channel.ChannelHandlerContext;

import com.card.common.MessageComm;
import com.card.message.JsonMessageCenter;
import com.card.notice.NoticeManager;
import com.card.setting.GameSetting;
import com.card.storage.UserStorage;
import com.xiaoao.net.db.Entity;
import com.xiaoao.net.global.Global;
import com.xiaoao.net.json.message.JsonMessage;
import com.xiaoao.net.utils.MathUtils;
import com.xiaoao.net.utils.StringUtil;
import com.xiaoao.net.utils.TimeUtils;

/**
 * 用户基础数据
 * @author xiaoaogame
 *
 */
public class UserBase extends EntityBase{
	private String primaryKey;//唯一id
	protected String username;// 登录名称
	protected int charmValue;
	protected int score;
	protected int fatherId;
	protected int julebuid;//用户列表品的俱乐部id
	protected int roomId;
	protected int julebustate;//0没有加入俱乐部    1申请 中      2加入成功
	protected String matchId;
	
	protected Date lastLoginDate;//最后一次登陆时间
	protected transient ChannelHandlerContext ctx;// 角色socket
	
	//==================================懒惰加载========================================================
	private UserCurrency userCurrency;//资产信息
	/**
	 * 玩家邮件系统
	 */
	private UserMail userMail;
	private UserAdvice userAdvice;
	/**
	 * 玩家数据统计
	 */
	private UserStatistics userStatistics;
	/**
	 * 玩家背包
	 */
	private UserStorage userStorage;
	private UserExtra userExtra;//
	private UserPlayBacks userPlayBacks;
	
	public UserBase(Entity userEntity) {
		super(userEntity);
		setPrimaryKey(userEntity.getKey().getName());
	}

	public int getJulebustate() {
		return julebustate;
	}
	
	
	public String getJulebustateStr() {
		
		if (this.julebustate ==0 ) {
			return "";
		} 
		if (this.julebustate ==1) {
			return "申请加入";
		}
		return "已经加入";
	}

	public void setJulebustate(int julebustate) {
		this.julebustate = julebustate;
	}



	public int getJulebuid() {
		return julebuid;
	}

	public void setJulebuid(int julebuid) {
		this.julebuid = julebuid;
	}

	public String getPrimaryKey() {
		return primaryKey;
	}

	public void setUsername(String username) {
		this.username = username;
	}
	
	public String getUsername() {
		return username;
	}
	
	
	public int getCharmValue() {
		return charmValue;
	}
	public int getScore() {
		return score;
	}
	public int getFatherId() {
		return fatherId;
	}

	public void setFatherId(int fatherId) {
		this.fatherId = fatherId;
	}

	public UserCurrency getUserCurrency() {
		return userCurrency;
	}

	public void setUserCurrency(UserCurrency userCurrency) {
		this.userCurrency = userCurrency;
	}

	public UserMail getUserMail() {
		return userMail;
	}

	public void setUserMail(UserMail userMail) {
		this.userMail = userMail;
	}

	public UserAdvice getUserAdvice() {
		return userAdvice;
	}

	public void setUserAdvice(UserAdvice userAdvice) {
		this.userAdvice = userAdvice;
	}

	public UserStatistics getUserStatistics() {
		return userStatistics;
	}

	public void setUserStatistics(UserStatistics userStatistics) {
		this.userStatistics = userStatistics;
	}

	public UserStorage getUserStorage() {
		return userStorage;
	}

	public void setUserStorage(UserStorage userStorage) {
		this.userStorage = userStorage;
	}

	public UserExtra getUserExtra() {
		return userExtra;
	}

	public void setUserExtra(UserExtra userExtra) {
		this.userExtra = userExtra;
	}

	public UserPlayBacks getUserPlayBacks() {
		return userPlayBacks;
	}

	public void setUserPlayBacks(UserPlayBacks userPlayBacks) {
		this.userPlayBacks = userPlayBacks;
	}

	public void setPrimaryKey(String primaryKey) {
		this.primaryKey = primaryKey;
	}

	public void setCharmValue(int charmValue) {
		this.charmValue = charmValue;
	}

	public void setScore(int score) {
		this.score = score;
	}

	public Date getLastLoginDate() {
		return lastLoginDate;
	}
	public void setLastLoginDate(Date lastLoginDate) {
		this.lastLoginDate = lastLoginDate;
	}


	public UserCurrency userCurrency() {
		if( null == this.userCurrency ) {
			this.userCurrency = GetDataObjectFromProperty(StringParam.Curreny, UserCurrency.class );
			userCurrency.LateInit(this);
		}
		return userCurrency;
	}
	
	public UserMail userMail(){
		if(userMail == null){
			userMail = GetDataObjectFromProperty(StringParam.UserMail, UserMail.class);
			userMail.LateInit(this);
		}
		return userMail;
	}
	
	public UserAdvice userAdvice(){
		if(userAdvice == null){
			userAdvice = GetDataObjectFromProperty(StringParam.UserAdvice, UserAdvice.class);
			userAdvice.LateInit(this);
		}
		return userAdvice;
	}
	
	public UserStatistics userStatistics(){
		if(userStatistics == null){
			userStatistics = GetDataObjectFromProperty(StringParam.UserStatistics, UserStatistics.class);
			userStatistics.LateInit(this);
		}
		return userStatistics;
	}
	public UserStorage userStorage(){
		if(userStorage == null){
			userStorage = GetDataObjectFromProperty(StringParam.UserStorage, UserStorage.class);
			userStorage.LateInit(this);
		}
		return userStorage;
	}
	public UserExtra userExtra() {
		if (null == this.userExtra) {
			this.userExtra = GetDataObjectFromProperty(StringParam.UserExtra, UserExtra.class);
			userExtra.LateInit(this);
		}
		return userExtra;
	}
	public UserPlayBacks userPlayBacks() {
		if (null == this.userPlayBacks) {
			this.userPlayBacks = GetDataObjectFromProperty(StringParam.UserPlayBacks, UserPlayBacks.class);
			userPlayBacks.LateInit(this);
		}
		return userPlayBacks;
	}
	
	public void addScore(int addScore) {
		this.score += addScore;
	}
	public void addCharmValue(int addCharmValue) {
		this.charmValue += addCharmValue;
	}
	public void setRoomId(int roomId) {
		if(this.roomId != roomId) {
			this.roomId = roomId;
			Store();
		}
	}
	public int getRoomId() {
		return roomId;
	}

	/**
	 * 对外接口,保存数据到数据库
	 * @return
	 */
	public UserBase Store() {
		StoreInternal();
		if (userEntityModified) {
			saveOrUpdateEntity();
			this.userEntityModified = false;
		}
		return this;
	}
	
	/**
	 * 数据加载之后,同步数据到对象
	 */
	public void initBase() {
		this.primaryKey = super.getPrimaryKey();
		this.lastLoginDate = (Date)getObjectProperty(StringParam.LastLoginDate);
		this.charmValue = getIntProperty(StringParam.CharmValue);
		this.score = getIntProperty(StringParam.Score);
		this.fatherId = getIntProperty(StringParam.FatherId);
		this.roomId = getIntProperty(StringParam.RoomId);
		this.matchId = getStringProperty(StringParam.MatchId);
		this.julebuid = getIntProperty(StringParam.Julebuid);
		this.julebustate = getIntProperty(StringParam.Julebustate);
		
		userCurrency();
		userStorage();
//		userAdvice();
		userCurrency();
		userStatistics();
		userMail();
		userPlayBacks();
	}
	
	/**
	 * 同步数据到entity
	 */
	private void StoreInternal(){
		//同步货币信息
		StorePlayerDataComponent(userCurrency,StringParam.Curreny);
		//同步玩家邮件系统
		StorePlayerDataComponent(userMail, StringParam.UserMail);
		StorePlayerDataComponent(userAdvice, StringParam.UserAdvice);		
		//同步玩家数据
		StorePlayerDataComponent(userStatistics, StringParam.UserStatistics);
		//同步背包信息
		StorePlayerDataComponent(userStorage,StringParam.UserStorage);
		StorePlayerDataComponent(userExtra, StringParam.UserExtra);
		StorePlayerDataComponent(userPlayBacks, StringParam.UserPlayBacks);

		StoreProperty(StringParam.LastLoginDate, lastLoginDate);
		StoreProperty(StringParam.CharmValue, charmValue);
		StoreProperty(StringParam.Score, score);
		StoreProperty(StringParam.FatherId, fatherId);
		StoreProperty(StringParam.RoomId, roomId);
		StoreProperty(StringParam.MatchId, matchId);
		StoreProperty(StringParam.Julebuid, julebuid);
		StoreProperty(StringParam.Julebustate, julebustate);
	}
	
	private void StorePlayerDataComponent(UserDataComponent component, String propertyName ){
		if( null != component && true == component.Changed() ){
			StoreJSONObject( component, propertyName );
			component.ClearChangedFlag();
		}
	}
	
	public ChannelHandlerContext getCtx() {return ctx;}
	public void setCtx(ChannelHandlerContext ctx) {this.ctx = ctx;}
	
	/**
	 * 检查是否重置每日数据
	 * @return
	 */
	public boolean chkResetData() {
		Date now = new Date();
		if(TimeUtils.isSameDay(now, lastLoginDate)) {
			return false;
		}
		this.lastLoginDate = now;
		return true;
	}
	public String getIp() {return "127.0.0.1";}
	
	public void fillMsg(JsonMessage message) {
		message.addProperty("id", primaryKey);//id
		message.addProperty("username", username);//登录名
		message.addProperty("charmValue", charmValue);//魅力值
		message.addProperty("FatherId", fatherId);//上级
		message.addProperty("ip", getIp());//ip
		message.addProperty("score", score);//积分
		//message.addProperty("ip", getIp());//积分
		//游戏配置信息
		GameSetting.getInstance().fillConfMsg(message);
		//当前所有的公告
		message.addProperty("notices", NoticeManager.getInstance().getNotices());
		//我的资产信息
		message.addProperty(StringParam.Curreny, userCurrency());
		//我的统计信息
		message.addProperty(StringParam.UserStatistics, userStatistics());
		//我的礼物信息
		message.addProperty(StringParam.UserStorage, userStorage());
		userExtra().fillMsg(message);
		message.addProperty(StringParam.UserPlayBacks, userPlayBacks());

		//邮件信息
		userMail().fillMsg(message);
	}
	
	private void fillPlayerDataComponentToMsg(String propertyName ,UserDataComponent component, JsonMessage message){
		if( null != component && true == component.Changed() ){
			message.addProperty(propertyName, component);
		}
	}
	
	
	protected void fillChangeMsg(JsonMessage message) {
		message.addProperty("charmValue", charmValue);//魅力值
		message.addProperty("score", score);//积分
		fillPlayerDataComponentToMsg(StringParam.Curreny, userCurrency(),message);
		fillPlayerDataComponentToMsg(StringParam.UserStatistics, userStatistics(),message);
		fillPlayerDataComponentToMsg(StringParam.UserStorage, userStorage(),message);
		fillPlayerDataComponentToMsg(StringParam.UserPlayBacks, userPlayBacks(),message);
		
		//邮件信息
		if(userMail().Changed()) userMail.fillMsg(message);
		if(userExtra().Changed()) userExtra.fillMsg(message);
//		if(userStatistics().Changed()) userStatistics().fillMsg(message);
	}
	
	protected void fillFriendMsg(JsonMessage message) {
		message.addProperty("userId", getPrimaryKey());//魅力值
		message.addProperty("charmValue", charmValue);//魅力值
		message.addProperty("score", score);//积分
		message.addProperty("ip", getIp());//积分
		message.addProperty(StringParam.Curreny, userCurrency());
		message.addProperty(StringParam.UserStatistics, userStatistics());
		userExtra().fillMsg(message);
	}
	
	public String getMatchId() {
		return matchId;
	}

	public void setMatchId(String matchId) {
		if(!StringUtil.equals(this.matchId, matchId)) {
			this.matchId = matchId;
			Store();
		}
	}

	public void sendUserUpdateMessage() {
		JsonMessage message = new JsonMessage(MessageComm.S2C_UserUpdate);
		fillChangeMsg(message);
		JsonMessageCenter.getInstance().sendMessage(message, this);
		Store();
	}
	
	public void addMessage2Queue(JsonMessage message) {
		
	}
	public void closeCtx() {
		if(ctx != null) {
			try {
				Global.logErrorMessage("!!!!!!!!!!!!!关闭连接："+getPrimaryKey());
//				ctx.getChannel().disconnect();
				ctx.getChannel().close();
				ctx.setAttachment(null);
				this.ctx = null;
			} catch (Exception e) {
				Global.logErrorMessage(e);
			}
		}
	}
}
